<template>
  <div>
    <el-container>
      <el-row class="avue-view">
        <el-col :span="5">
          <basic-container>
            <div
              class="avue-tree__filter label"
            >
              <div>
                <div>部门组织架构</div>
                <i class="el-icon-refresh" @click="refreshTree" />
              </div>
              <div style="padding-top: 10px">
                <el-input v-model="filterText" :size="treeOption.size" placeholder="输入关键字过滤" />
              </div>
            </div>
            <!--            树形结构-->
            <el-tree
              ref="tree"
              v-loading="treeLoading"
              :data="treeData"
              :node-key="nodeKey"
              :filter-node-method="treeFilterNode"
              :expand-on-click-node="false"
              :default-expand-all="true"
              :draggable="true"
              @node-click="treeClickHandle"
              @node-contextmenu="contextMenuHandle"
            >
              <div slot-scope="{ node, data }" class="avue-tree__item">
                <div class="avue-tree__title">
                  {{ data[labelKey] }}
                </div>
              </div>
            </el-tree>
            <!--          右键显示弹出层-->
            <div v-show="contextMenuShow" :style="{left: contextMenuLeft, top: contextMenuTop}" class="el-context-menu">
              <div class="el-context-menu-box">
                <div @click="addDeptHandle">
                  <span>新增</span><i class="el-icon-plus" />
                </div>
                <div @click="editDeptHandle">
                  <span>编辑</span><i class="el-icon-edit" />
                </div>
                <div @click="delDeptHandle">
                  <span>删除</span><i class="el-icon-delete" />
                </div>
                <div @click="addDeptUserHandle">
                  <span>新增人员</span><i class="el-icon-user" />
                </div>
              </div>
            </div>
            <el-dialog
              :title="treeFormTitle"
              :visible.sync="treeFormShow"
              modal-append-to-body
              append-to-body
              @close="treeFormHide"
            >
              <avue-form
                ref="treeForm"
                v-model="treeForm"
                :option="treeFormOption"
                @submit="treeFormSubmit"
              >
                <template slot="pname" slot-scope="{item}">
                  <el-input v-if="treeType =='add'" :value="item.name" />
                  <el-input v-else :value="item.id" />
                </template>
              </avue-form>
            </el-dialog>
          </basic-container>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud
              ref="crud"
              v-model="form"
              :option="option"
              :data="data"
              :before-open="beforeOpen"
              :page="page"
              :upload-delete="uploadDelete"
              :upload-before="uploadBefore"
              :upload-after="uploadAfter"
              @row-del="rowDel"
              @row-update="rowUpdate"
              @row-save="rowSave"
              @search-change="searchChange"
              @search-reset="searchReset"
              @refresh-change="refresh"
              @selection-change="selectionChange"
              @current-change="currentChange"
              @size-change="sizeChange"
              @on-load="onLoad"
            >
              <template slot="menuLeft">
                <el-button
                  type="danger"
                  size="medium"
                  icon="el-icon-delete"
                  plain
                  @click="handleDelete"
                >
                  删 除
                </el-button>
                <el-button
                  type="primary"
                  size="medium"
                  plain
                  icon="el-icon-refresh"
                  @click="handleReset"
                >
                  密码重置
                </el-button>
              </template>
              <template
                slot="deptId"
                slot-scope="{row}"
              >
                <el-tag v-if="row.deptName">
                  {{ row.deptName }}
                </el-tag>
              </template>
              <template slot="status" slot-scope="{row}">
                <el-tooltip :content="'用户状态:' + (row.status? '正常': '禁用')" placement="top">
                  <el-switch
                    v-model="row.status"
                    :active-value="true"
                    :inactive-value="false"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="changeStatus(row)"
                  />
                </el-tooltip>
              </template>
              <template slot="warningForm">
                <el-alert
                  :closable="false"
                  :title="`新增用户默认密码为：${defaultPasswd}`"
                  type="warning"
                  effect="dark"
                />
              </template>
              <template slot="statusForm" slot-scope="{row}">
                <el-tooltip :content="'账号状态:' + (row.status? '正常': '禁用')" placement="top">
                  <el-switch
                    v-model="row.status"
                    :disabled="statusDisabled"
                    :active-value="true"
                    :inactive-value="false"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  />
                </el-tooltip>
              </template>
              <!--            提权按钮-->
              <template slot="menu" slot-scope="{row,$index}">
                <el-button type="warning" icon="el-icon-key" size="medium" @click.stop="authorize(row,$index)">
                  角色/授权
                </el-button>
              </template>
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
    </el-container>
    <div>
      <in-feed-adsense
        v-if="enableAds"
        data-ad-layout-key="-6t+ed+2i-1n-4w"
        data-ad-slot="2627967536"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import upload from '@/api/sys/upload'
import { uniqueStr } from '@/util/NumberUtil'
import config from '@/config'
import { isEmail, isMobile } from '@/util/ValidateUtil'

const addDeptAction = 'sys/dept/addSysDept'
const updateDeptAction = 'sys/dept/updateSysDept'
const removeDeptAction = 'sys/dept/removeSysDept'

const addUserAction = 'sys/user/addUser'
const updateUserAction = 'sys/user/updateUser'
const removeUserAction = 'sys/user/removeUserById'
const removeUsersAction = 'sys/user/removeUsersById'
const getUserByIdAction = 'sys/user/getUserById'
const getUserPageListAction = 'sys/user/getUserPageList'

const resetUserPasswdBatchAction = 'sys/user/resetUserPasswdBatch'
const lockUserAction = 'sys/user/lockUser'
const getDeptTreeAction = 'sys/dept/getSysDeptTreeList'
const getRoleListAction = 'sys/role/getSysRoleList'
const getUserRoleByUserIdAction = 'sys/user/getUserRoleByUserId'
const delFileAction = 'sys/upload/deleteFile'

export default {
  name: 'UserDept',
  data () {
    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮箱！'))
      } else if (!isEmail(value)) {
        callback(new Error('输入的邮箱非法!'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码！'))
      } else if (!isMobile(value)) {
        callback(new Error('输入的手机号码非法!'))
      } else {
        callback()
      }
    }
    // const validatePass = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入密码'))
    //   } else {
    //     callback()
    //   }
    // }
    // const validatePass2 = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请再次输入密码'))
    //   } else if (value !== this.form.passwd) {
    //     callback(new Error('两次输入密码不一致!'))
    //   } else {
    //     callback()
    //   }
    // }
    const statusDic = [
      {
        label: '启用',
        value: true
      },
      {
        label: '禁用',
        value: false
      }
    ]
    return {
      enableAds: config.website.enableAds,
      authorizeBox: false,
      statusDisabled: false,
      defaultPasswd: config.defaultPasswd,
      filterText: '',
      treeData: [],
      treeLoading: false,
      treeOption: {
        nodeKey: 'id',
        addBtn: true,
        checkStrictly: true,
        menu: true,
        size: 'small',
        props: {
          labelText: '部门名称',
          label: 'deptName',
          value: 'id',
          children: 'children'
        }
      },
      contextMenuShow: false,
      contextMenuLeft: '',
      contextMenuTop: '',
      treeFormShow: false,
      treeFormTitle: '',
      treeType: '',
      treeNode: {},
      treeObj: {},
      treeForm: {},
      treeFormOption: {
        labelWidth: 100,
        emptyBtn: false,
        column: [{
          label: '上级部门名称',
          prop: 'pname',
          labelWidth: 130,
          span: 24,
          disabled: true,
          slot: true
        }, {
          label: '部门(节点)名称',
          prop: 'deptName',
          labelWidth: 130,
          span: 24,
          rules: [
            {
              required: true,
              message: '请输入部门名称',
              trigger: 'blur'
            }
          ]
        }]
      },
      // 右边的列表
      form: {},
      data: [],
      selectionList: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      init: {
        roleTree: [],
        deptTree: []
      },
      option: {
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        menuType: 'icon',
        selection: true,
        searchShow: true,
        searchMenuSpan: 5,
        viewBtn: true,
        dialogHeight: 450,
        dialogType: 'drawer',
        editTitle: '编辑用户账号',
        column: [
          {
            // 默认密码提示语
            prop: 'warning',
            hide: true,
            span: 24,
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
            showColumn: false,
            labelWidth: 1,
            formslot: true
          },
          {
            label: '登录账号',
            prop: 'userName',
            search: true,
            rules: [{
              required: true,
              message: '请输入登录账号',
              trigger: 'blur'
            }],
            span: 24
          },
          {
            label: '用户昵称',
            prop: 'nickName',
            search: false,
            rules: [{
              required: false,
              message: '请输入用户昵称',
              trigger: 'blur'
            }]
          },
          {
            label: '所属角色',
            prop: 'roleId',
            type: 'select',
            hide: true,
            drag: true,
            multiple: true,
            showColumn: false,
            props: {
              label: 'roleName',
              value: 'id'
            },
            dicData: [],
            value: null,
            rules: [{
              required: true,
              message: '请选择所属角色',
              trigger: 'click'
            }]
          },
          {
            label: '所属部门',
            prop: 'deptId',
            type: 'tree',
            multiple: false,
            expand: true,
            defaultExpandAll: true,
            dicData: [],
            value: null,
            props: {
              label: 'deptName',
              value: 'id',
              children: 'children'
            },
            slot: true,
            rules: [{
              required: true,
              message: '请选择所属部门',
              trigger: 'click'
            }]
          },
          {
            label: '手机号码',
            prop: 'phone',
            search: true,
            overHidden: true,
            rules: [{
              validator: validatePhone,
              trigger: 'blur'
            }]
          },
          {
            label: '电子邮箱',
            prop: 'email',
            hide: true,
            search: true,
            overHidden: true,
            rules: [{
              validator: validateEmail,
              trigger: 'blur'
            }]
          },
          {
            label: '性别',
            prop: 'sex',
            type: 'select',
            hide: false,
            dicData: [
              {
                label: '男',
                value: 1
              },
              {
                label: '女',
                value: 2
              },
              {
                label: '未知',
                value: 3
              }
            ],
            value: 3
          },
          {
            label: '生日',
            type: 'date',
            prop: 'birth',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            hide: true,
            pickerOptions: {
              disabledDate (time) {
                return time.getTime() >= Date.now()
              }
            },
            rules: [{
              required: false,
              message: '请输入生日',
              trigger: 'click'
            }]
          },
          {
            label: '地址',
            type: 'textarea',
            prop: 'address',
            hide: true,
            maxlength: 200,
            span: 24,
            showWordLimit: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true
          },
          {
            label: '头像',
            prop: 'avatar',
            type: 'upload',
            listType: 'picture-img',
            hide: false,
            span: 24,
            limit: 1,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            data: {
              userId: 0,
              token: '0'
            },
            canvasOption: {
              text: '头像',
              ratio: 0.1
            },
            propsHttp: {
              res: 'data',
              fileName: 'file'
            },
            action: upload.UPLOAD_URL
          },
          {
            label: '账号状态',
            prop: 'status',
            type: 'switch',
            slot: true,
            formslot: true,
            rules: [{
              required: true,
              message: '请设置用户账号状态',
              trigger: 'blur'
            }],
            dicData: statusDic,
            value: true
          }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions', 'userInfo', 'website', 'sidebar']),
    addFlag () {
      return this.treeType === 'add' || this.treeType === 'parentAdd'
    },
    labelKey () {
      return this.treeOption.props.label
    },
    nodeKey () {
      return this.treeOption.nodeKey
    },
    ids () {
      const ids = []
      this.selectionList.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted () {
    this.fetchDeptTree()
    this.fetchRoleList()
  },
  methods: {
    // 授权
    authorize (row, index) {
      this.authorizeBox = true
      this.option.editTitle = '账号授权对应角色'
      const nickNameIndex = this.$refs.crud.findColumnIndex('nickName')
      // 隐藏特定列
      this.switchFieldStatus(nickNameIndex, false)
      this.$refs.crud.rowEdit(row, index)
    },
    switchFieldStatus (nickNameIndex, status) {
      // 隐藏特定列
      this.option.column[nickNameIndex].editDisplay = status
      // deptId
      this.option.column[nickNameIndex + 2].editDisplay = status
      // phone
      this.option.column[nickNameIndex + 3].editDisplay = status
      // email
      this.option.column[nickNameIndex + 4].editDisplay = status
      // sex
      this.option.column[nickNameIndex + 5].editDisplay = status
      // birth
      this.option.column[nickNameIndex + 6].editDisplay = status
      // address
      this.option.column[nickNameIndex + 7].editDisplay = status
      // avatar
      this.option.column[nickNameIndex + 8].editDisplay = status
      // status
      this.option.column[nickNameIndex + 9].editDisplay = status
    },
    // 上传相关
    uploadBefore (file, done, loading) {
      // 如果你想修改file文件,由于上传的file是只读文件，必须复制新的file才可以修改名字，完后赋值到done函数里,如果不修改的话直接写done()即可
      // const newFile = new File([file], '1234', { type: file.type })
      done(file)
    },
    uploadAfter (res, done, loading) {
      done()
    },
    uploadDelete (column) {
      const avatar = this.form.avatar
      return this.$confirm('是否确定移除头像？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const delData = { url: avatar }
        return this.$store.dispatch(delFileAction, delData)
      }).then((res) => {
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.$message({
            type: 'success',
            message: '删除头像成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '删除头像失败,请稍后再试!'
          })
        }
      }).catch(() => {

      })
    },
    treeFilterNode (value, data) {
      if (!value) { return true }
      return data[this.labelKey].includes(value)
    },
    refreshTree () {
      this.fetchDeptTree()
    },
    treeClickHandle (data, node, el) {
      const deptId = data.id
      this.query = { deptId }
      this.page.currentPage = 1
      this.onLoad(this.page)
    },
    contextMenuHandle (e, data, node, el) {
      const self = this
      this.contextMenuTop = e.pageY - 50 - 35 + 'px'
      // 修复菜单定位不准问题
      const sidebarWidth = this.sidebar.opened ? 200 : 50
      this.contextMenuLeft = e.pageX - sidebarWidth + 'px'
      this.contextMenuShow = true
      this.treeObj = data
      this.treeNode = node
      document.onclick = function (ev) {
        // if (ev.target !== self.$refs.tree) {
        self.contextMenuShow = false
        // }
      }
    },
    // 点击新增
    addDeptHandle () {
      this.treeType = 'add'
      this.treeForm.pname = this.treeObj.deptName
      this.treeForm.pid = this.treeObj.id
      this.treeFormTitle = `新增部门(上级部门:${this.treeForm.pname})`
      this.deptFormShow()
    },
    // 点击编辑
    editDeptHandle () {
      this.treeType = 'edit'
      this.treeForm = this.deepClone(this.treeObj)
      const pname = this.treeNode.parent.data.deptName
      this.treeForm.pname = pname || '顶级节点'
      this.treeFormTitle = `编辑部门(部门:${this.treeForm.pname})`
      this.deptFormShow()
    },
    deptFormShow () {
      this.treeFormShow = true
      setTimeout(() => {
        this.$refs.treeForm.clearValidate()
      }, 0)
    },
    treeFormHide () {
      this.treeFormShow = false
      this.treeNode = {}
      this.treeObj = {}
      this.$refs.treeForm.resetForm()
      this.$refs.treeForm.clearValidate()
    },
    treeFormSubmit (form, done) {
      this.addFlag ? this.addDept(form, done) : this.editDept(form, done)
    },
    addDept (form, done) {
      const addData = {
        pid: form.pid,
        deptName: form.deptName
      }
      this.$store.dispatch(addDeptAction, addData).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.treeFormHide()
          this.fetchDeptTree()
          this.$message({
            type: 'success',
            message: '保存操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '保存数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    editDept (form, done) {
      const updateData = {
        id: form.id,
        deptName: form.deptName
      }
      this.$store.dispatch(updateDeptAction, updateData).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.treeFormHide()
          this.fetchDeptTree()
          this.$message({
            type: 'success',
            message: '编辑操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '编辑数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    delDeptHandle (node, data) {
      const callback = () => {
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.id === data.id)
        children.splice(index, 1)
      }
      this.$confirm(`是否删除部门${this.treeObj.deptName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.treeLoading = true
          const idParams = { id: this.treeObj.id }
          return this.$store.dispatch(removeDeptAction, idParams)
        })
        .then((res) => {
          this.treeLoading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.treeFormHide()
            this.fetchDeptTree()
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
            callback()
          } else {
            this.treeLoading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {
          this.treeLoading = false
        })
    },
    addDeptUserHandle () {
      // 设置对应的部门id
      this.form.deptId = this.treeObj.id
      const index = this.$refs.crud.findColumnIndex('deptId')
      this.option.column[index].disabled = true
      this.$refs.crud.rowAdd()
    },
    // -------------------------------------------------------------------------
    // 切换状态
    changeStatus (row) {
      this.$confirm('确认要' + (row.status ? "'启用'" : "'停用'") + '用户吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const idParams = { id: row.id, status: row.status, version: row.version }
        return this.$store.dispatch(updateUserAction, idParams)
      }).then((res) => {
        this.loading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '用户状态切换成功!'
          })
        } else {
          this.loading = false
          row.status = !row.status
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '切换用户状态失败,请稍后再试!'
          })
        }
      }).catch(() => {
        this.loading = false
        row.status = !row.status
      })
    },
    // 刷新
    refresh ({ page, searchForm }) {
      this.onLoad(page)
    },
    // 列表
    rowSave (row, loading, done) {
      loading()
      this.$store.dispatch(addUserAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '保存数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    rowUpdate (row, index, loading, done) {
      loading()
      this.$store.dispatch(updateUserAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '编辑数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    rowDel (row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(removeUserAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {
          this.loading = false
        })
    },
    searchReset () {
      this.query = {}
      this.page.currentPage = 1
      this.onLoad(this.page)
    },
    searchChange (params, done) {
      done()
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
    },
    selectionChange (list) {
      this.selectionList = list
    },
    selectionClear () {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },
    handleDelete () {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { ids: this.ids }
          return this.$store.dispatch(removeUsersAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量删除操作成功!'
            })
            this.onLoad(this.page)
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '批量删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {
          this.loading = false
        })
    },
    handleReset () {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm(`确定将选择账号密码重置为${this.defaultPasswd}?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { ids: this.ids }
          return this.$store.dispatch(resetUserPasswdBatchAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量重置用户密码操作成功!'
            })
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '批量重置用户密码失败,请稍后再试!'
            })
          }
        })
    },
    // 不再使用,直接使用状态栏
    lockUser (row) {
      const statusText = row.locked ? '解禁' : '禁用'
      this.$confirm(`确定${statusText}选中该用户?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(lockUserAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '禁用用户密码操作成功!'
            })
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '禁用用户密码失败,请稍后再试!'
            })
          }
        })
    },
    beforeOpen (done, type) {
      const userNameIndex = this.$refs.crud.findColumnIndex('userName')
      const nickNameIndex = this.$refs.crud.findColumnIndex('nickName')
      if (['edit', 'view'].includes(type)) {
        // 对应formslot的字段手动进行disabled
        this.option.column[userNameIndex].disabled = true
        if (type === 'view') {
          this.statusDisabled = true
        } else {
          this.statusDisabled = false
          // 设置对应的字段
          if (!this.authorizeBox) {
            this.option.editTitle = '用户账号编辑'
            this.switchFieldStatus(nickNameIndex, true)
          }
        }
        const idParams = { id: this.form.id }
        this.$store.dispatch(getUserByIdAction, idParams).then((res) => {
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.form = res.data
            if (this.form.deptId <= 0) {
              this.form.deptId = null
              // this.$set(this.form, 'deptId', null)
            }
            // 获取对应的用户的角色信息
            this.fetchUserRoleByUserId(idParams)
            // 设置头像上传组件
            this.setUserAvatarUploadInfo()
          } else {
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '查询数据失败,请稍后再试!'
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
      } else {
        this.statusDisabled = false
        this.option.column[userNameIndex].disabled = false
      }
      this.authorizeBox = false
      done()
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    onLoad (page, params = {}) {
      this.loading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.query))
      this.$store.dispatch(getUserPageListAction, queryData).then((res) => {
        this.loading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const data = res.data
          this.page.total = parseInt(data.total)
          this.data = data.records
          this.selectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    },
    fetchDeptTree () {
      this.treeLoading = true
      this.$store.dispatch(getDeptTreeAction).then((res) => {
        const resCode = res.code
        if (resCode === 0) {
          this.treeLoading = false
          this.treeData = res.data
          // 设置右边的用户的部门树数据
          const index = this.$refs.crud.findColumnIndex('deptId')
          this.option.column[index].dicData = res.data
        }
      }).catch((err) => {
        console.log(err)
        this.treeLoading = false
      })
    },
    fetchRoleList () {
      this.$store.dispatch(getRoleListAction).then((res) => {
        const resCode = res.code
        if (resCode === 0) {
          const index = this.$refs.crud.findColumnIndex('roleId')
          this.option.column[index].dicData = res.data
        }
      })
    },
    // 编辑/查看弹出框
    setUserAvatarUploadInfo () {
      const index = this.$refs.crud.findColumnIndex('avatar')
      this.option.column[index].data.userId = this.userInfo.id
      this.option.column[index].data.token = uniqueStr()
    },
    fetchUserRoleByUserId (data) {
      // const index = this.$refs.crud.findColumnIndex('roleId')
      this.form.roleId = null
      this.$store.dispatch(getUserRoleByUserIdAction, data).then((res) => {
        const resCode = res.code
        if (resCode === 0) {
          const roleData = res.data
          const roleIds = roleData.map((r) => {
            return r.roleId
          })
          let roleCode = null
          if (roleIds && roleIds[0] > 0) {
            // this.$set(this.form, 'roleId', null)
            roleCode = roleIds
          }
          this.form.roleId = roleCode
        }
      })
    }
  },
  head () {
    return {
      title: '用户部门管理 | ' + this.website.name,
      meta: [
        { hid: 'description', name: 'description', content: '用户部门管理' }
      ]
    }
  }
}
</script>

<style scoped>
.avue-view {
  padding: 0 10px!important;
  width: 100%;
  box-sizing: border-box;
}
  .label {
    display: flex;
    flex-direction: column;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: initial;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: flex-start;
    height: 60px;
    background-color: #fff;
    letter-spacing: 1px;
  }
  .label div {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    font-size: 15px;
    /*color: #008ad3;*/
    -webkit-box-flex: 1;
    -ms-flex: 1;
    flex: 1;
    min-width: 100px;
  }

  /*右键弹出框*/
.el-context-menu {
  position: absolute;
  z-index: 9999
}

.el-context-menu .el-context-menu-box {
  -webkit-box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  width: 160px;
  padding: 5px 0;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  top: 0
}

.el-context-menu .el-context-menu-box._append {
  right: calc(-100% - 5px);
  top: -5px
}

.el-context-menu .el-context-menu-box>div {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 35px;
  font-size: 13px;
  cursor: pointer;
  padding: 0 15px;
  color: #666;
  position: relative
}

.el-context-menu .el-context-menu-box>div span {
  height: 35px;
  line-height: 35px;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1
}

.el-context-menu .el-context-menu-box>div:hover {
  background-color: #f7f7f7;
  color: #000
}

.el-context-menu .el-context-menu-box>div i:first-child {
  margin-right: 5px
}

.el-context-menu .el-context-menu-box>div i:last-child {
  margin-left: 5px
}

.el-context-menu .el-context-menu-box>div._active {
  background-color: #f7f7f7;
  color: #000
}

.el-context-menu .el-context-menu-box>div._ellipsis span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap
}

.el-context-menu .el-context-menu-box>div._disabled span,.el-context-menu .el-context-menu-box>div._disabled span:hover {
  color: #ccc
}

</style>
